using Avalonia.BiliBili.Units;
using Avalonia.BiliBili.Views.ChildViews.Search;
using Avalonia.BiliBili.Windows;
using Avalonia.Extensions.Controls;
using Avalonia.Extensions.Event;
using Bilibili.Common;
using Bilibili.Model.Common;
using Bilibili.Model.Search;
using DynamicData;
using PCLUntils.Objects;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Avalonia.BiliBili.Views.ChildViews
{
    public partial class SearchUser : ChildView
    {
        private int PageNum { get; set; } = 1;
        private ObservableCollection<SearchUserItem> Items { get; }
        public SearchUser()
        {
            InitializeComponent();
            Items = [];
        }
        public override void AfterInitializeComponent()
        {
            userList.ItemsSource = Items;
            userList.ItemClick += Users_ItemClick;
        }
        private void Users_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.IsLeftClick && e.ClickItem is ListViewItem item && item.Content is SearchUserItem userItem)
                    Navigater.OpenWindow<UserInfoWindow>(userItem.mid);
            }
            catch { }
        }
        public override void Callback(object data)
        {
            RunOnUiThread(async () =>
            {
                if (data is InvokeData<string> info)
                {
                    if (info.Clear)
                        Items.Clear();
                    string order = GetTag(orderBy), type = GetTag(userType);
                    var orderCondition = "&order=&order_sort=";
                    if (order.IsNotEmpty())
                    {
                        var orders = order.Split('-');
                        orderCondition = $"&order={orders.ElementAt(0)}&order_sort={orders.ElementAt(1)}";
                    }
                    var typeCondition = $"&user_type={type}";
                    var result = await Base.Client.GetUsers(info.Data, orderCondition, typeCondition, PageNum);
                    if (result.IsNotEmpty())
                    {
                        if (result.IsSuccess())
                        {
                            var ls = result.Data["result"].ToObject<List<SearchUserItem>>();
                            if (ls != null && ls.Count > 0)
                                Items.AddRange(ls);
                        }
                        else
                            PopupToast.Show(result?.Message);
                    }
                }
            });
        }
    }
}